import {
  _decorator,
  CCInteger,
  Component,
  find,
  instantiate,
  Label,
  Prefab,
  randomRange,
  Vec3,
} from "cc";
import { Sun } from "../Sun";
const { ccclass, property } = _decorator;

// 管理类 做成单例模式 全局能够进行使用 类创建成静态的
@ccclass("SunManager")
export class SunManager extends Component {
  private static _instance: SunManager = null;

  @property({ type: CCInteger, tooltip: "总阳光值" })
  private sunPoint: number = 0;

  @property({ type: Label, tooltip: "阳光值显示" })
  public sumPointLabel: Label = null;

  @property(CCInteger)
  produceNatureSunTime: number = 0; // 自然阳光生产的时间

  @property(Prefab)
  sunPrefab: Prefab = null;

  /**
   * 静态访问 器 获取实例
   */
  public static get Instance(): SunManager {
    return this._instance;
  }

  /**
   * 公共访问器 获取阳光值
   */
  public get SunPoint(): number {
    return this.sunPoint;
  }

  protected onLoad(): void {
    // 确保全局只有一个实例
    if (SunManager._instance == null) {
      SunManager._instance = this;
    } else {
      console.log("SunManager is already exist");
      this.node.destroy();
      return;
    }
  }

  protected start(): void {
    this.updateSunPointLabel();
    // this.schedule(this.produceNatureSun, this.produceNatureSunTime);
    setTimeout(() => {
      // this.schedule(this.produceNatureSun, this.produceNatureSunTime);
    }, 5000);
  }

  /**
   * 更新阳光值Label显示
   */
  private updateSunPointLabel(): void {
    this.sumPointLabel.string = this.sunPoint.toString();
  }

  /**
   * 减少阳光值的方法
   * @param point 阳光值
   */
  public subSun(point: number): void {
    this.sunPoint -= point;
    if (this.sunPoint < 0) {
      this.sunPoint = 0;
    }
    this.updateSunPointLabel();
  }

  /**
   * 增加阳光值的方法
   * @param point 阳光值
   */
  public addSun(point: number): void {
    this.sunPoint += point;
    this.updateSunPointLabel();
  }
  /**
   * 生产自然阳光
   */
  produceNatureSun() {
    const sunNode = instantiate(this.sunPrefab);
    const xPosition = randomRange(-360, 510);
    sunNode.setPosition(new Vec3(xPosition, 10, 0));
    sunNode.parent = find("Canvas/ForeGround");
    sunNode.getComponent(Sun).linearTo(xPosition);
  }
}
